package com.ljx.itbbs.server.article.event.handler;

import com.ljx.itbbs.server.article.domain.enums.LikeEnum;
import com.ljx.itbbs.server.article.event.DislikeEvent;
import com.ljx.itbbs.server.article.event.LikeEvent;
import com.ljx.itbbs.server.article.service.ArticleService;
import com.ljx.itbbs.server.article.service.CommentService;
import com.ljx.itbbs.server.article.service.LikeRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-04-21  10:23
 */
@Component
public class DislikeEventHandler {


    @Autowired
    private CommentService commentService;

    @Autowired
    private LikeRecordService likeRecordService;

    @Autowired
    private ArticleService articleService;

    /**
     * 取消点赞
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = DislikeEvent.class, fallbackExecution = true)
    public void reduceLikeNum(DislikeEvent event) {
        if (event.getType().equals(LikeEnum.ARTICLE.getType())){
            articleService.reduceLikeNum(event.getObjId());
        } else if(event.getType().equals(LikeEnum.COMMENT.getType())){
            commentService.reduceLikeNum(event.getObjId(), event.getCommentType());
        }
    }

    /**
     * 删除保存记录
     * @param event
     */
    @Async
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT, classes = DislikeEvent.class, fallbackExecution = true)
    public void deleteLikeRecord(DislikeEvent event) {
        likeRecordService.deleteListRecord(event.getUserId(), event.getLikeObj(), event.getType());
    }

}
